/**
 *
 */
package ua.at.tsvetkov.samizdat.activities;

import ua.at.tsvetkov.samizdat.Const;
import ua.at.tsvetkov.samizdat.Key;
import ua.at.tsvetkov.samizdat.R;
import ua.at.tsvetkov.samizdat.adapters.AdtBooks;
import ua.at.tsvetkov.samizdat.data.Book;
import ua.at.tsvetkov.samizdat.data.Data;
import ua.at.tsvetkov.samizdat.data.DataDownloader;
import ua.at.tsvetkov.samizdat.data.WrongFieldCountException;
import ua.at.tsvetkov.application.AppConfig;
import ua.at.tsvetkov.util.Log;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * @author A.Tsvetkov 2011, http://tsvetkov.at.ua, al@ukr.net
 */
public class AcGenreBooks extends AcTemplate {

	private static final int	DIALOG_ORDER_SELECT	= 3;
	private String					genreCode;
	private int						genreCount;
	private String					sort;
	private String					urlStr;
	private String					fileName;
	protected View					currentView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		genreCode = getIntent().getExtras().getString("code");
		try {
			genreCount = Integer.parseInt(getIntent().getExtras().getString("count"));
		} catch (NumberFormatException e) {
			Log.e("Неправильное количество", e);
			finish();
		}
		// http://samlib.ru/cgi-bin/areader?q=janr&jnum=8&order=title&page=1&pagelen=20
		generateSortingString();
		dataDownloader = new DataDownloader(this, (ProgressDialog) onCreateDialog(DIALOG_LOAD), urlStr, Const.LIST_VIEW_COUNT);
		startPosition = 0;
		dataDownloader.setOnCompleteLoadListener(standartNotifier);
		addListView();
		dataDownloader.download(genreCount, fileName, true, false);
		adapter = new AdtBooks(this, dataDownloader, Const.LIST_VIEW_COUNT);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (showMore(position, listView))
					return;

				try {
					currentView = view;
					String[] data = dataDownloader.getDataFields(position - 1, Data.BOOK_FIELDS_COUNT);
					Book book = new Book(data);
					book.openAcBook(AcGenreBooks.this);
				} catch (WrongFieldCountException e) {
					e.printStackTrace();
				}
			}

		});
	}

	private void generateSortingString() {
		sort = AppConfig.getString(Key.GENRE_BOOKS_SORTING, Const.ORDER_TITLE);
		urlStr = Const.URL_GENRE_BOOKS + genreCode + "&order=" + sort + "&page=1&pagelen=" + genreCount;
		fileName = Const.FILE_ROOT + ".genre_" + genreCode + "_" + sort + ".txt";
	}

	@Override
	protected void onResume() {
		adapter.refreshData();
		adapter.notifyDataSetChanged();
		super.onResume();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		super.onKeyDown(keyCode, event);
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			showDialog(DIALOG_ORDER_SELECT);
			return true;
		}
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
			return true;
		}
		return false;
	}

	/*
	 * (non-Javadoc)
	 * @see ua.at.tsvetkov.samizdat.activities.AcTemplate#onCreateDialog(int)
	 */
	@Override
	public Dialog onCreateDialog(int id) {
		switch (id) {
			case DIALOG_ORDER_SELECT: {
				final CharSequence[] items = { AcGenreBooks.this.getText(R.string.ORDER_TITLE), AcGenreBooks.this.getText(R.string.ORDER_TYPE), AcGenreBooks.this.getText(R.string.ORDER_SIZE),
						AcGenreBooks.this.getText(R.string.ORDER_BALL), AcGenreBooks.this.getText(R.string.ORDER_DATE) };

				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle(AcGenreBooks.this.getText(R.string.ORDER));
				int position = -1;
				if (sort.equals(Const.ORDER_TITLE))
					position = 0;
				if (sort.equals(Const.ORDER_TYPE))
					position = 1;
				if (sort.equals(Const.ORDER_SIZE))
					position = 2;
				if (sort.equals(Const.ORDER_BALL))
					position = 3;
				if (sort.equals(Const.ORDER_DATE))
					position = 4;
				builder.setSingleChoiceItems(items, position, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						switch (item) {
							case 0: {
								AppConfig.putSetting(Key.GENRE_BOOKS_SORTING, Const.ORDER_TITLE, true);
								break;
							}
							case 1: {
								AppConfig.putSetting(Key.GENRE_BOOKS_SORTING, Const.ORDER_TYPE, true);
								break;
							}
							case 2: {
								AppConfig.putSetting(Key.GENRE_BOOKS_SORTING, Const.ORDER_SIZE, true);
								break;
							}
							case 3: {
								AppConfig.putSetting(Key.GENRE_BOOKS_SORTING, Const.ORDER_BALL, true);
								break;
							}
							case 4: {
								AppConfig.putSetting(Key.GENRE_BOOKS_SORTING, Const.ORDER_DATE, true);
								break;
							}
						}
						removeDialog(DIALOG_ORDER_SELECT);
						generateSortingString();
						dataDownloader.setProgress((ProgressDialog) onCreateDialog(DIALOG_LOAD));
						dataDownloader.setUrl(urlStr);
						startPosition = 0;
						dataDownloader.download(genreCount, fileName, true, false);
					}
				});
				return builder.create();
			}
		}
		return super.onCreateDialog(id);
	}

}
